package com.campus.event.service.impl;

import com.campus.event.entity.CheckIn;
import com.campus.event.repository.CheckInRepository;
import com.campus.event.service.CheckInService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CheckInServiceImpl implements CheckInService {
    private final CheckInRepository checkInRepository;

    @Override
    @Transactional
    public CheckIn checkIn(Long userId, Long eventId, String qrCode) {
        // 检查是否已签到
        if (hasCheckedIn(userId, eventId)) {
            throw new RuntimeException("Already checked in");
        }
        CheckIn checkIn = new CheckIn();
        checkIn.setUserId(userId);
        checkIn.setEventId(eventId);
        checkIn.setQrCode(qrCode);
        checkIn.setTimestamp(LocalDateTime.now());
        return checkInRepository.save(checkIn);
    }

    @Override
    public CheckIn getCheckIn(Long id) {
        return checkInRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Check-in not found"));
    }

    @Override
    public List<CheckIn> getUserCheckIns(Long userId) {
        return checkInRepository.findByUserId(userId);
    }

    @Override
    public List<CheckIn> getEventCheckIns(Long eventId) {
        return checkInRepository.findByEventId(eventId);
    }

    @Override
    public boolean hasCheckedIn(Long userId, Long eventId) {
        return checkInRepository.existsByUserIdAndEventId(userId, eventId);
    }
} 